package controller

import (
	"net/http"
	"time"

	"gitee.com/chuanjinge/gopkgserv/api/response"
	"gitee.com/chuanjinge/gopkgserv/internal/dao"
	"gitee.com/chuanjinge/gopkgserv/pkg/auth"

	"github.com/gin-gonic/gin"
)

// NewExamController 控制器
type NewExamController struct{}

// NewExam 生成新考卷
func (nc *NewExamController) NewExam(c *gin.Context) {
	token := c.GetHeader("Authorization")
	claims, err := auth.ParseToken(token)
	if err != nil {
		c.JSON(http.StatusOK, response.BaseResponse{
			Code: 401,
			Msg:  "token无效",
			Data: nil,
		})
		return
	}
	userId := claims.UserID

	// 随机选题
	singleQuestions, err := dao.RandomQuestionsByType(1, 5)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.BaseResponse{Code: 500, Msg: err.Error()})
		return
	}
	multipleQuestions, err := dao.RandomQuestionsByType(2, 5)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.BaseResponse{Code: 500, Msg: err.Error()})
		return
	}
	judgeQuestions, err := dao.RandomQuestionsByType(3, 5)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.BaseResponse{Code: 500, Msg: err.Error()})
		return
	}

	allQuestions := append(singleQuestions, multipleQuestions...)
	allQuestions = append(allQuestions, judgeQuestions...)

	// 创建考卷
	now := time.Now()
	exam := dao.ExamExams{
		UserID:     int(userId),
		Status:     1,
		CreatedAt:  &now,
		UpdatedAt:  &now,
		FinishedAt: nil,
	}
	err = dao.CreateExamWithQuestions(&exam, allQuestions)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.BaseResponse{Code: 500, Msg: err.Error()})
		return
	}
	c.JSON(http.StatusOK, response.Success(gin.H{"examId": exam.ID}))
}
